const md5 = require('crypto'),
    fs = require("fs"),
    path = require('path');
let main = {};
//md5加密
main.md5 = (str) => {
    let hex = md5.createHash('md5');
    hex.update(str);
    return hex.digest('hex').toString('hex');
}

//获取json信息
main.getJson = (fileName) => {
    try {
        if (fs.existsSync(fileName)) {
            delete require.cache[require.resolve(fileName)];
            let val = require(fileName);
            return val;
        } else return false;
    } catch (error) {
        return false;
    }
}

//转化时间戳
main.date = (intTime, formatStr) => {
    let Time = intTime && intTime || +new Date,
        regx = 'xxxxxxxxxxxxx';
    let dateTime = Time + regx.substr(Time.toString().length, 13);
    dateTime = new Date(parseInt(dateTime.replace(/x/g, 0)));
    formatStr = formatStr ? formatStr : 'yyyy/MM/dd hh:mm:ss';
    let year = dateTime.getFullYear(),
        month = dateTime.getMonth() + 1,
        date = dateTime.getDate(),
        houres = dateTime.getHours(),
        minutes = dateTime.getMinutes(),
        seconds = dateTime.getSeconds(),
        milliseconds = full(dateTime.getMilliseconds() + "", "0", 3, true);
    return formatStr.replace(/yyyy|YYYY/, year).replace(/yy|YY/, year - parseInt(year / 100) * 100).replace(/MM|mm/,
        month > 9 ? month.toString() : '0' + month).replace(/M/g, month).replace(/dd|DD/, date > 9 ? date.toString() : '0' + date).replace(
        /d|D/g, date).replace(/hh|HH/, houres > 9 ? houres.toString() : '0' + houres).replace(/h|H/g, houres).replace(/ii|II/,
        minutes > 9 ? minutes.toString() : '0' + minutes).replace(/i|I/g, minutes).replace(/ss|SS/,
        seconds > 9 ? seconds.toString() : '0' + seconds).replace(/s|S/g, seconds).replace(/fff/g, milliseconds);
}

//修改文件
main.write = (fileName, data) => {
    return new Promise((resolve, reject)=>{
        fs.writeFile(fileName, data, (err) => {
            if (err) reject();
            else resolve();
        });
    })
}

const full = (str, ch, count, isLeft) => {
    while (str.length < count)
        str = isLeft ? ch + str : str + ch;
    return str;
};
module.exports = main;